<template>
  <div id="userManagePage" class="user-manage-container">
    <!-- 搜索表单 -->
    <div class="search-form-container">
      <a-form layout="inline" :model="searchParams" class="search-form">
        <a-form-item label="账号">
          <a-input 
            v-model:value="searchParams.userAccount" 
            placeholder="输入账号" 
            allow-clear 
            class="search-input"
            @change="handleSearch"
          />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input 
            v-model:value="searchParams.userName" 
            placeholder="输入用户名" 
            allow-clear 
            class="search-input"
            @change="handleSearch"
          />
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="选择用户角色"
            allow-clear
            class="search-input"
            @change="handleSearch"
          >
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="简介">
          <a-input 
            v-model:value="searchParams.userProfile" 
            placeholder="输入简介" 
            allow-clear 
            class="search-input"
            @change="handleSearch"
          />
        </a-form-item>
        <a-form-item>
          <a-button 
            @click="handleReset" 
            class="reset-button"
            type="default"
            size="middle"
          >
            <template #icon><ClearOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        @change="doTableChange"
        :locale="locale"
        :bordered="true"
        :row-key="record => record.id"
        class="user-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userAvatar'">
            <a-image 
              :src="record.userAvatar" 
              :width="50" 
              :preview="true"
              class="user-avatar"
            />
          </template>
          <template v-else-if="column.dataIndex === 'userRole'">
            <div v-if="record.userRole === 'admin'">
              <a-tag color="green" class="role-tag">管理员</a-tag>
            </div>
            <div v-else>
              <a-tag color="blue" class="role-tag">普通用户</a-tag>
            </div>
          </template>
          <template v-if="column.dataIndex === 'createTime'">
            <span class="time-text">{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button 
                type="primary"
                @click="showEditModal(record)"
                class="edit-button"
              >
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-button 
                danger 
                @click="doDelete(record.id)"
                class="delete-button"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加编辑对话框 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑用户"
      @ok="handleEditSubmit"
      :confirmLoading="editLoading"
    >
      <a-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        layout="vertical"
      >
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="简介" name="userProfile">
          <a-textarea
            v-model:value="editForm.userProfile"
            placeholder="请输入简介"
            :rows="4"
          />
        </a-form-item>
        <a-form-item label="用户角色" name="userRole">
          <a-select v-model:value="editForm.userRole" placeholder="请选择用户角色">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, DeleteOutlined, ClearOutlined, EditOutlined } from '@ant-design/icons-vue'
import { deleteUserUsingPost, listUserVoByPageUsingPost, updateUserUsingPost } from '@/api/userController.ts'
import dayjs from 'dayjs'

// 添加中文语言配置
const locale = {
  filterTitle: '筛选',
  filterConfirm: '确定',
  filterReset: '重置',
  filterEmptyText: '无筛选项',
  selectAll: '全选当页',
  selectInvert: '反选当页',
  selectionAll: '全选所有',
  sortTitle: '排序',
  expand: '展开行',
  collapse: '关闭行',
  triggerDesc: '点击降序',
  triggerAsc: '点击升序',
  cancelSort: '取消排序'
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    align: 'center',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    align: 'center',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    sorter: true,
    sortDirections: ['ascend', 'descend', 'ascend'],
  },
  // {
  //   title: '更新时间',
  //   dataIndex: 'updateTime',
  //   sorter: true,
  //   sortDirections: ['ascend', 'descend', 'ascend'],
  // },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

const doDelete = async (id: number) => {
  const res = await deleteUserUsingPost({ id })
  console.log('res', res)
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    await fetchData()
  } else {
    message.error('删除失败')
  }
}

// 数据
const dataList = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
  userAccount: '',
  userName: '',
  userRole: undefined,
  userProfile: '',
})

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 表格变化之后，重新获取数据
const doTableChange = (pagination: any, filters: any, sorter: any) => {
  // 处理分页
  searchParams.current = pagination.current
  searchParams.pageSize = pagination.pageSize

  // 处理排序
  if (sorter.field) {
    searchParams.sortField = sorter.field
    searchParams.sortOrder = sorter.order === 'ascend' ? 'ascend' : 'descend'
  } else {
    // 没有排序时，恢复默认排序
    searchParams.sortField = 'createTime'
    searchParams.sortOrder = 'ascend'
  }

  fetchData()
}

// 添加防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: any = null
  return function (...args: any[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 处理搜索
const handleSearch = debounce(() => {
  searchParams.current = 1 // 重置页码
  fetchData()
}, 300) // 300ms 的防抖延迟

// 添加重置函数
const handleReset = () => {
  // 重置所有搜索条件
  searchParams.userAccount = ''
  searchParams.userName = ''
  searchParams.userRole = undefined
  searchParams.userProfile = ''
  searchParams.current = 1
  // 重新获取数据
  fetchData()
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    locale: {
      items_per_page: '条/页',
      jump_to: '跳至',
      jump_to_confirm: '确定',
      page: '页',
      prev_page: '上一页',
      next_page: '下一页',
      prev_5: '向前 5 页',
      next_5: '向后 5 页',
      prev_3: '向前 3 页',
      next_3: '向后 3 页',
    }
  }
})

// 编辑相关状态
const editModalVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: 0,
  userName: '',
  userProfile: '',
  userRole: '',
})

// 编辑表单验证规则
const editRules = {
  userName: [{ required: true, message: '请输入用户名' }],
  userRole: [{ required: true, message: '请选择用户角色' }],
}

// 显示编辑对话框
const showEditModal = (record: API.UserVO) => {
  editForm.id = record.id
  editForm.userName = record.userName || ''
  editForm.userProfile = record.userProfile || ''
  editForm.userRole = record.userRole || ''
  editModalVisible.value = true
}

// 提交编辑表单
const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    const res = await updateUserUsingPost({
      id: editForm.id,
      userName: editForm.userName,
      userProfile: editForm.userProfile,
      userRole: editForm.userRole,
    })
    if (res.data.code === 0) {
      message.success('更新成功')
      editModalVisible.value = false
      // 刷新数据
      await fetchData()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    editLoading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.user-manage-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.search-form-container {
  background-color: #fff;
  padding: 16px 24px; /* 减小上下内边距 */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 10px;
}

.search-form {
  display: flex;
  flex-wrap: nowrap;
  gap: 12px;
  align-items: center;
  justify-content: flex-start;
  overflow-x: auto;
  padding-bottom: 4px;
}

.search-form::-webkit-scrollbar {
  height: 6px;
}

.search-form::-webkit-scrollbar-thumb {
  background-color: #d9d9d9;
  border-radius: 3px;
}

.search-form::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

.search-input {
  width: 140px;
  flex-shrink: 0;
}

/* 移除搜索按钮相关样式，因为不再需要 */
.search-button {
  display: none;
}

.table-container {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.user-table {
  margin-top: 16px;
}

.user-avatar {
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #f0f0f0;
  transition: all 0.3s;
}

.user-avatar:hover {
  transform: scale(1.05);
  border-color: #1890ff;
}

.role-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.time-text {
  color: #666;
  font-size: 14px;
}

.delete-button {
  transition: all 0.3s;
}

.delete-button:hover {
  transform: scale(1.05);
}

.edit-button {
  transition: all 0.3s;
}

.edit-button:hover {
  transform: scale(1.05);
}

/* 调整按钮间距 */
:deep(.ant-space) {
  gap: 8px !important;
}

/* 美化编辑对话框样式 */
:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

:deep(.ant-modal-title) {
  font-weight: 600;
  color: #262626;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #262626;
}

:deep(.ant-input),
:deep(.ant-input-textarea),
:deep(.ant-select-selector) {
  border-radius: 4px;
  border-color: #d9d9d9;
  transition: all 0.3s;
}

:deep(.ant-input:hover),
:deep(.ant-input-textarea:hover),
:deep(.ant-select-selector:hover) {
  border-color: #40a9ff;
}

:deep(.ant-input:focus),
:deep(.ant-input-textarea:focus),
:deep(.ant-select-selector:focus) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.ant-pagination-item-active) {
  border-color: #1890ff;
}

:deep(.ant-pagination-item-active a) {
  color: #1890ff;
}

/* 添加表格单元格居中对齐的样式 */
:deep(.ant-table-cell) {
  text-align: center !important;
}

/* 确保表头也居中对齐 */
:deep(.ant-table-thead > tr > th) {
  text-align: center !important;
  background-color: #fafafa;
  font-weight: 600;
}

.reset-button {
  margin-left: 4px;
  color: #666;
  border-color: #d9d9d9;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 0 12px;
  height: 32px;
  border-radius: 4px;
  font-size: 14px;
  background: linear-gradient(to bottom, #ffffff, #f5f5f5);
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.02);
  border: 1px solid #e8e8e8;
}

.reset-button:hover {
  color: #1890ff;
  border-color: #1890ff;
  background: linear-gradient(to bottom, #ffffff, #e6f7ff);
  box-shadow: 0 2px 6px rgba(24, 144, 255, 0.1);
}

.reset-button:active {
  color: #096dd9;
  border-color: #096dd9;
  background: linear-gradient(to bottom, #e6f7ff, #bae7ff);
  box-shadow: 0 1px 2px rgba(24, 144, 255, 0.2);
}

/* 调整图标样式 */
.reset-button :deep(.anticon) {
  font-size: 14px;
  transition: all 0.3s;
  color: #8c8c8c;
}

.reset-button:hover :deep(.anticon) {
  transform: rotate(180deg);
  color: #1890ff;
}

.reset-button:active :deep(.anticon) {
  color: #096dd9;
}
</style>

